package com.lindroy.viewpagerfragmentpractice

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.lindroy.viewpagerfragmentpractice.fragment.AFragment
import com.lindroy.viewpagerfragmentpractice.fragment.BFragment
import com.lindroy.viewpagerfragmentpractice.fragment.BaseFragment
import kotlinx.android.synthetic.main.activity_view_pager2.*

class ViewPager2Activity : AppCompatActivity() {

    private val fragmentTags = listOf<String>(
        AFragment::class.java.simpleName,
        BFragment::class.java.simpleName
    )

    private val adapter = object : FragmentStateAdapter(this) {

        /**
         * FragmentStateAdapter 将 Fragment 添加 FragmentManager 时的 tag 为 "f" + holder.getItemId()
         */
        fun getItem(position: Int) = supportFragmentManager.findFragmentByTag("f$position") as? BaseFragment

        override fun getItemId(position: Int) = position.toLong()

        override fun getItemCount() = fragmentTags.size

        override fun createFragment(position: Int) = when (fragmentTags[position]) {
            AFragment::class.java.simpleName -> AFragment()
            BFragment::class.java.simpleName -> BFragment()
            else -> AFragment()
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_view_pager2)


        //offscreenPageLimit默认为-1，此时只有页面显示时才会创建Fragment
        viewPager.offscreenPageLimit = fragmentTags.size
        viewPager.adapter = adapter

        button.setOnClickListener {
            adapter.getItem(viewPager.currentItem)?.showMessage("hello")
            //获取通过 supportFragmentManager 获取 Fragment
//            (supportFragmentManager.fragments[viewPager.currentItem] as? BaseFragment)?.showMessage("hello")

        }
    }

}